import json
import re

from django.contrib.auth import login, authenticate, logout
from django.core.mail import send_mail
from django.http import JsonResponse
# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.cart.utils import merge_cart_cookie_to_redis
from apps.users.models import User, Address
from apps.users.utils import generate_verify_email_url, check_verify_email_url
from celery_tasks.email.tasks import send_verify_mail
from utils.viewmixin import LoginMixin


class UsernameCountView(View):
    def get(self, request, username):
        # 1.接收用户名
        print(username)
        # 2.根据用户名查数据库
        count = User.objects.filter(username=username).count()
        # 3.返回响应
        return JsonResponse({'count': count, 'code': 0, 'errmsg': 'OK'})


class RegisterView(View):
    def post(self, request):
        # 1.接收请求
        body_byte = request.body
        # 获取json格式数据，转为字典
        body_dict = json.loads(body_byte)

        # 2.获取数据
        username = body_dict.get("username")
        password = body_dict.get("password")
        password2 = body_dict.get("password2")
        mobile = body_dict.get("mobile")
        sms_code = body_dict.get("sms_code")
        allow = body_dict.get("allow")

        # 3.验证数据
        # 3.1验证是否为空，有没有传输
        # all里传入列表，如果列表里任一元素为flase或者空，结果就是flase。
        if not all([username, password, password2, mobile, sms_code, allow]):
            return JsonResponse({"code": "400", "errmsg": "缺少必要参数"})
        # 3.2正则验证
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({"code": "400", "errmsg": "用户名格式错误"})

        # 4.生成用户保存到数据库
        # User.objects.create(username=username, password=password, mobile=mobile)

        # 短信验证码验证
        # 从redis里获取短信验证码
        redis_cli = get_redis_connection("code")
        redis_sms_code = redis_cli.get("sms_%s" % mobile)

        # 判断是否过期
        if redis_sms_code is None:
            return JsonResponse({"code": "400", "errmsg": "短信验证码已过期"})

        # 和用户发过来的进行对比
        if redis_sms_code.decode() != sms_code:
            return JsonResponse({"code": "400", "errmsg": "短信验证码输入错误"})

        # 密码加密
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except:
            return JsonResponse({"code": "400", "errmsg": "用户信息保存失败，请检查信息。"})

        # 状态保持
        login(request, user)
        # 5.返回响应
        return JsonResponse({"code": "400", "errmsg": "OK"})


class LoginView(View):
    def post(self, request):
        # 1.接受数据
        body = request.body
        data_dict = json.loads(body)
        username = data_dict.get("username")
        password = data_dict.get("password")
        remembered = data_dict.get("remembered")
        print(password)

        # 2.验证数据是否为空
        if not all([username, password]):
            return JsonResponse({"code": "400", "errmsg": "参数不全"})

        # 根据用户传入的username的值，判断是手机号还是用户名
        # 然后设置用户验证是用手机号登录还是用户名
        if re.match('1[3-9]\d{9}', username):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'

        # 3.验证用户名和密码是否正确
        # 如果用户名和密码输入正确，返回user对象，否则返回none
        user = authenticate(username=username, password=password)
        if user is None:
            return JsonResponse({"code": "400", "errmsg": "用户名或密码错误"})

        # 4.状态保持
        login(request, user)

        # 5.判断是否记住登录
        if remembered:
            # 记住登录，默认为两周
            request.session.set_expiry(None)
        else:
            # 不记住登录，浏览器关闭时session过期
            request.session.set_expiry(0)

        # 登录成功后首页显示用户名
        response = JsonResponse({"code": "0", "errmsg": "ok"})
        response.set_cookie('username', user.username, max_age=3600 * 34 * 5)
        # 合并购物车调用
        response1 = merge_cart_cookie_to_redis(request=request, user=user, response=response)

        # 6.返回响应
        return response1


class LogoutView(View):
    def delete(self, request):
        # 1.调用logout清空状态保持的session
        logout(request)

        # 2.删除cookie里的username
        response = JsonResponse({"code": "0", "errmsg": "ok"})
        response.delete_cookie('username')

        # 3.返回响应
        return response


class UserInfoView(LoginMixin, View):
    def get(self, request):
        info_data = {
            "username": request.user.username,
            "mobile": request.user.mobile,
            "email": request.user.email,
            "email_active": request.user.email_active
        }

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            "info_data": info_data
        })


class SaveEmailView(View):

    def put(self, request):
        # 获取数据
        json_body = request.body
        data_dict = json.loads(json_body)
        email = data_dict.get("email")
        # 校验数据

        if not email:
            return JsonResponse({"code": "400", "errmsg": "邮箱地址不能为空"})

        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({"code": "400", "errmsg": "邮箱地址格式错误"})

        # 保存邮箱地址
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            print(e)
            return JsonResponse({"code": "400", "errmsg": "邮箱保存失败"})

        # 发送邮件
        print("发送邮件")
        subject = "美多商城邮箱验证"
        recipient_list = [email]
        # 添加token
        token = generate_verify_email_url(request.user.id)

        verify_url = "http://www.meiduo.site:8080/success_verify_email.html?token=%s" % token
        # 修改发送内容为链接
        html_message = '尊敬的用户您好！' \
                       '感谢您使用美多商城。' \
                       '您的邮箱为：%s 。请点击此链接激活您的邮箱：' \
                       '%s' % (email, verify_url)

        # send_mail(subject, message, from_email, recipient_list)
        # 异步发送短信

        send_verify_mail.delay(subject=subject, html_message=html_message, recipient_list=recipient_list)
        print("发送成功")

        # 返回响应
        return JsonResponse({"code": "0", "errmsg": "ok"})


class EmailVerifyView(View):
    def put(self, request):
        # 1获取参数
        token = request.GET.get("token")

        # 2校验参数
        if token is None:
            return JsonResponse({"code": "400", "errmsg": "缺少token"})
        # 3解密获取user_id
        user_id = check_verify_email_url(token)

        # 4判断user_id是否为空
        if user_id is None:
            return JsonResponse({"code": "400", "errmsg": "token错误"})
        try:
            # 5查询用户 数据
            user = User.objects.get(id=user_id)
        except Exception as e:
            print(e)
            return JsonResponse({"code": "400", "errmsg": "查询不到用户"})

        # 6修改用户邮箱激活字段为True
        user.email_active = True
        user.save()

        # 7返回响应
        return JsonResponse({"code": "0", "errmsg": "ok"})


class AddressCreateView(LoginMixin, View):
    def post(self, request):
        # 1.接受请求
        addr_body = request.body
        data_dict = json.loads(addr_body)
        # 2.获取参数
        receiver = data_dict.get("receiver")
        province_id = data_dict.get("province_id")
        city_id = data_dict.get("city_id")
        district_id = data_dict.get("district_id")
        place = data_dict.get("place")
        mobile = data_dict.get("mobile")
        tel = data_dict.get("tel")
        email = data_dict.get("email")
        print('---', receiver, province_id, city_id, district_id, place, mobile, '---')
        # 3.验证参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({"code": 400, "errmsg": "参数不全"})
        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return JsonResponse({"code": 400, "errmsg": "参数mobile有误"})
        #
        # if tel:
        #     if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
        #         return JsonResponse({"code": 400, "errmsg": "参数tel有误"})
        #
        # if email:
        #     if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
        #         return JsonResponse({"code": 400, "errmsg": "参数email有误"})

        # 4.保存数据到数据库
        user = request.user
        try:

            address = Address.objects.create(
                user=user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )

            address.save()
            print('保存成功')
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "保存到数据库失败"})

        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        # 5.返回响应
        return JsonResponse({"code": 0, "errmsg": "ok", 'address': address_dict})


class AddressShowView(LoginMixin, View):
    def get(self, request):
        # 1.获取用户对象
        user = request.user

        # 2.查询当前用户的所有地址信息
        addresses = Address.objects.filter(user=user, is_deleted=False)

        # 3.转为字典数据
        addresses_list = []
        for address in addresses:
            addresses_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })

        # 4.返回响应
        return JsonResponse({'code': 0, "errmsg": "ok", "addresses": addresses_list})


class AddressUpdateChangeView(LoginMixin, View):
    def put(self, request, address_id):
        """修改地址"""
        # 接收参数
        json_dict = json.loads(request.body)
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        # 判断地址是否存在,并更新地址信息
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '更新地址失败'})

        # 构造响应数据
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应更新地址结果
        return JsonResponse({'code': 0, 'errmsg': '更新地址成功', 'address': address_dict})

    def delete(self, request, address_id):
        """删除"""
        try:
            address = Address.objects.get(id=address_id)
            address.is_deleted = True
            address.save()
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "删除失败"})

        return JsonResponse({'code': 0, "errmsg": "删除地址成功"})


class ChangePasswordView(LoginMixin, View):
    def put(self, request):
        # 接收参数
        dict = request.body
        data_dict = json.loads(dict)
        old_password = data_dict.get('old_password')
        new_password = data_dict.get('new_password')
        new_password2 = data_dict.get('new_password2')

        # 校验参数
        if not all([old_password, new_password, new_password2]):
            return JsonResponse({"code": 400, "errmsg": "密码参数不全"})

        ret = request.user.check_password(old_password)
        print('-------------', ret)
        if not ret:
            return JsonResponse({"code": 400, "errmsg": "原始密码不正确"})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return JsonResponse({'code': 400, 'errmsg': '密码最少8位,最长20位'})

        if new_password != new_password2:
            return JsonResponse({"code": 400, "errmsg": "两次密码输入不一致"})

        # 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '保存密码失败'})

        # 清除状态保持
        logout(request)
        response = JsonResponse({'code': 0, "errmsg": "ok"})
        response.delete_cookie('username')
        # 响应密码修改结果，重定向到登录页面
        return response
